package controller

import (
	"fmt"
	"github.com/gin-gonic/gin"
	alipay "github.com/smartwalle/alipay/v3"
	"myproject/utils"
	"strconv"
)

func Zhi(zhiPath *gin.RouterGroup) {
	//获取支付宝地址
	zhiPath.Use().GET("/getpayurl", getpayurl)
	//回调接口
	zhiPath.Use().GET("/callback", callback)

}

// 获取支付宝地址
func getpayurl(c *gin.Context) {
	utils.Init()
	money := c.Query("money")
	id := c.Query("id")
	var p = alipay.TradePagePay{}
	p.NotifyURL = "http://localhost:8000/zhi/callback?" + money + "id?" + id
	p.ReturnURL = "http://localhost:8000/zhi/callback?" + money + "id?" + id
	p.Subject = "要充值"
	number := utils.RandInt(10000, 99999)
	p.OutTradeNo = strconv.Itoa(number)
	p.TotalAmount = money
	p.ProductCode = "FAST_INSTANT_TRADE_PAY"

	url, err := utils.Client.TradePagePay(p)
	if err != nil {
		c.JSON(200, gin.H{
			"code": 20010,
			"mes":  "获取",
		})
		return
	}

	//fmt.Println(url)

	urll := url.Scheme + "://" + url.Host + url.Path + "?" + url.RawQuery
	c.JSON(200, gin.H{
		"code": 200,
		"url":  urll,
	})
}

// 支付宝回调接口
func callback(c *gin.Context) {
	//id := c.Query("uid")
	//难签
	order, err := utils.Client.GetTradeNotification(c.Request)
	alipay.AckNotification(c.Writer) // 确认收到通知消息
	fmt.Println(err, order)
	if order == nil {
		fmt.Println("验证失败")
	} else {
		fmt.Println(order)
		//var uid int
		//sql := "insert into Recharge (money, Userid) values (?,?)"
		//model.DB.Exec(sql,).Scan(&uid)
	}

}

// func pay(c *gin.Context) {
// 	var p = alipay.TradePagePay{}
// 	p.NotifyURL = "http://localhost:8000/news/callback"
// 	p.ReturnURL = "http://localhost:8000/news/callback"
// 	p.Subject = "修正了中文的 Bug"
// 	p.OutTradeNo = "111t1111rade_no_22201706230111212"
// 	p.TotalAmount = "10.00"
// 	p.ProductCode = "FAST_INSTANT_TRADE_PAY"

// 	url, err := utils.Client.TradePagePay(p)
// 	if err != nil {
// 		fmt.Println(nil)
// 	}
// 	fmt.Println(url)
// }

// func callBack(c *gin.Context) {
// 	// fmt.Println(c.Request)

// 	noti, err := utils.Client.GetTradeNotification(c.Request)
// 	if err != nil {
// 		fmt.Println("****")
// 		// c.Status(http.StatusInternalServerError)
// 		fmt.Println(err)
// 		return
// 	}
// 	fmt.Printf("订单号:%s;状态:%s\n", noti.OutTradeNo, noti.TradeStatus)
// 	c.String(http.StatusOK, "success")

// 	alipay.AckNotification(c.Writer) // 确认收到通知消息

// }
